<%@ page language="java" import="com.alibaba.fastjson.JSONObject" pageEncoding="UTF-8" %>
<%@ page import="okhttp3.*" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="org.apache.http.HttpResponse" %>
<%@ page import="org.apache.http.client.ClientProtocolException" %>
<%@ page import="org.apache.http.client.methods.HttpPatch" %>
<%@ page import="org.apache.http.conn.ssl.AllowAllHostnameVerifier" %>
<%@ page import="org.apache.http.conn.ssl.SSLConnectionSocketFactory" %>
<%@ page import="org.apache.http.entity.StringEntity" %>
<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %>
<%@ page import="org.apache.http.impl.client.HttpClients" %>
<%@ page import="org.apache.http.ssl.SSLContextBuilder" %>
<%@ page import="org.bouncycastle.jce.provider.BouncyCastleProvider" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="java.io.ByteArrayInputStream" %>
<%@ page import="java.io.FileNotFoundException" %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.nio.file.Files" %>
<%@ page import="java.nio.file.Paths" %>
<%@ page import="java.security.KeyStore" %>
<%@ page import="java.security.Security" %>
<%@ page import="java.security.cert.CertificateFactory" %>
<%@ page import="java.security.cert.X509Certificate" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%--流程退回调用QMS接口--%>
<%
    String url = "/sap/c4c/odata/v1/customer/CorporateAccountCollection('8B49A464E9AD1EEE8BED81EAFFC7BD9F')";
    JSONObject paramsJson = new JSONObject();
    paramsJson.put("Z_CustomerApproveStatus_KUT", "121");
    JSONObject result = sendOKHttpRequest(url,paramsJson.toJSONString());
   // String rootPtah = GCONST.getRootPath();
//    String certFilePath = rootPtah+"WEB-INF/lib/Cert/_.zhlxsemicon.com.cer";
//    out.println(">>>>>WeaXmyksqlcPMPAction>>>>>certFilePath=" + certFilePath+"<br/>");
//    String result = doPatch(url, paramsJson, certFilePath);
    out.println(">>>>>WeaXmyksqlcPMPAction>>>>>paramsJson=" + paramsJson+"<br/>");
    out.println(">>>>>WeaXmyksqlcPMPAction>>>>>result=" + result+"<br/>");
%>

<%!

    private static BaseBean baseBean = new BaseBean();
    private static final String URL = baseBean.getPropValue("zhlxc4", "url");
    private static final String USERNAME = baseBean.getPropValue("zhlxc4", "username");
    private static final String PASSWORD = baseBean.getPropValue("zhlxc4", "password");
    /**
     * 模拟发送 post 请求
     */
    public static String doPatch(String url, JSONObject paramsJson, String certFilePath) {
        // 构建POST请求 请求地址请更换为自己的。
        HttpPatch patch = new HttpPatch(url);
        String result = "";
        try {
            // 使用之前写的方法创建httpClient实例
            CloseableHttpClient httpClient = createSSLClient(certFilePath);
            String authorization = " Basic YWRtaW46MTIzNDU2";
            patch.addHeader("Authorization", authorization);
            patch.setEntity(new StringEntity(paramsJson.toString(), "UTF-8"));
            // 发送请求
            HttpResponse response = httpClient.execute(patch);
            result = response.getStatusLine().getStatusCode()+"";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("e1:" + e);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            System.out.println("e2:" + e);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("e3:" + e);
        }
        return result;

    }
    /**
     * 只信任特定机构颁发的证书
     * 安全,域名校验,建议使用
     *
     * @return
     */
    public static CloseableHttpClient createSSLClient(String certFilePath) {
        Security.addProvider(new BouncyCastleProvider());
        try {

            // load CA certificate
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInputStream = new ByteArrayInputStream(Files.readAllBytes(Paths.get(certFilePath)));
            X509Certificate caCert = null;
            while (caInputStream.available() > 0) {
                caCert = (X509Certificate) cf.generateCertificate(caInputStream);
            }
            caInputStream.close();
            KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
            caKs.load(null, null);
            caKs.setCertificateEntry("ca-certificate", caCert);
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(caKs, null).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            //SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return HttpClients.createDefault();
    }

    private static JSONObject sendOKHttpRequest(String apiType, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "fail";
        String message = "";
        String apiUrl = URL + Util.null2String(apiType);
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .hostnameVerifier(new AllowAllHostnameVerifier())
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("PATCH", body)
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            int responeCode = response.code();
            if (responeCode == 204) {
                code = "success";
                message = "调用成功";
            } else {
                message = "调用失败，响应码=" + responeCode;
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

%>




